package com.ibl.rover.lite.client.Activity;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

import com.ibl.rover.lite.client.Logger;
import com.ibl.rover.lite.client.R;
import com.ibl.rover.lite.client.RoverLiteClientActivity;
import com.ibl.rover.lite.client.Application.ApplicationContext;
import com.ibl.rover.lite.client.Sync.Parser.ResponseHandler;
import com.ibl.rover.lite.client.Sync.Parser.SyncRequestBuilder;
import com.ibl.rover.lite.client.Sync.Process.SyncronizationProcess;
import com.ibl.rover.lite.client.constants.RoverConstants.ServerErrCode;
import com.ibl.rover.lite.common.bean.CustomerBean;
import com.ibl.rover.lite.common.bean.SettingBean;
import com.ibl.rover.lite.common.db.Criteria;
import com.ibl.rover.lite.common.db.DatabaseManager;
import com.mobile.sync.client.Sync.impl.HTTPSyncImplFactory;
import com.mobile.sync.client.impl.AbstractBean;
import com.mobile.sync.client.impl.RequestBean;
import com.mobile.sync.client.impl.ResponseBean;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class RoverSyncActivity extends Activity implements OnClickListener {
	private Logger logger = new Logger();
	private ApplicationContext roverApp;
	private DatabaseManager manager = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.rover_sync);
		roverApp = (ApplicationContext) getApplication();
		manager = roverApp.getDatabaseManager();
		((Button) findViewById(R.id.sync_button)).setOnClickListener(this);
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.sync_button:
			sync();
			break;

		default:
			break;
		}

	}

	/**
	 * Save Server Setting
	 */
	private void saveSettings() {
		try {

			Criteria<SettingBean> criteria = roverApp.getDatabaseManager()
					.generateCriteria(SettingBean.class);
			List<SettingBean> list = criteria.execute();
			if (list.size() > 0) {
				if (roverApp.getHttpSyncImpl() == null) {
					SettingBean settingBean = list.get(0);
					roverApp.getAppParams()
							.getHttpConfiguration()
							.setServerPort(
									Integer.parseInt(settingBean
											.getServerPort()));
					roverApp.getAppParams().getHttpConfiguration()
							.setServerUrl(settingBean.getServerUrl());

					roverApp.setHttpSyncImpl(HTTPSyncImplFactory
							.getTransportAgent(roverApp.getAppParams()
									.getHttpConfiguration()));
					roverApp.getHttpSyncImpl().register(
							new ResponseHandler("[RESP_PARSE]"));
				}
			}

		} catch (Exception e) {
			logger.logException("saveSetting ", e);
		}
	}

	private void sync() {
		try {
			saveSettings();
			SyncRequestBuilder syncRequestBuilder = roverApp
					.getSyncRequestBuilder();
			RequestBean requestBean = syncRequestBuilder
					.buildSyncRequest(roverApp.getUserName());

			SyncronizationTask syncronizationTask = new SyncronizationTask(
					this, roverApp);

			syncronizationTask.execute(requestBean);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private class SyncronizationTask extends SyncronizationProcess {

		public SyncronizationTask(Context context,
				ApplicationContext roverContext) {
			super(context, roverContext);

		}

		@Override
		public void onResponseComplete(AbstractBean response) {
			logger.log("[onResponseComplete .. Starts]");
			if (null != response) {
				ResponseBean httpResponseMsg = (ResponseBean) response;
				logger.log("[Http Response Code : "
						+ httpResponseMsg.getServerResponseCode());
				logger.log("[Server Response Code : "
						+ httpResponseMsg.getMessage());
				int httpResponseCode = httpResponseMsg.getServerResponseCode();
				if (ResponseBean.HTTP_OK == httpResponseCode) {
					switch (httpResponseMsg.getMessageCode()) {
					case ServerErrCode.SUCCESS:
						doHandleSuccess();
						finish();
						break;
					default:
						doHandleFailure(httpResponseMsg.getMessageCode());
						break;
					}
				} else if (httpResponseCode > 400 && httpResponseCode < 500) {

					showErroDialog(2,
							"Connectivity to the Server is not Available");
				} else {

					showErroDialog(2,
							"Connectivity to the Server is not Available");
				}
			}
			logger.log("[onResponseComplete .. Ends]");

		}

		private void doHandleFailure(int messageCode) {
			try {
				showErroDialog(2, "Syncronization not completed Sucessfully");
			} catch (Exception e) {
				logger.logException("doHandle Faileure", e);
			}

		}

	}

	private void doHandleSuccess() {
		try {

			// manager.executeScaler("DELETE FROM APP_SETUP_BEAN");
			// manager.executeScaler("DELETE FROM CUSTOMER_BEAN");
			// manager.executeScaler("DELETE FROM ORDER_BEAN");
			// manager.executeScaler("DELETE FROM PRODUCT_BEAN");
			// manager.executeScaler("DELETE FROM PRODUCT_CATEGROY");
			// manager.executeScaler("DELETE FROM PRODUCT_ORDER_BEAN");
			// manager.executeScaler("DELETE FROM ROUTE_BEAN");
			// manager.executeScaler("DELETE FROM USER_BEAN");
			// getlogOut();
			// roverApp.getViewContext().clear();
//			showErroDialog(2, "Synchronization Completed Sucessfully");
			 roverApp.showMessage("Synchronization Completed Sucessfully",
			 Toast.LENGTH_LONG);
			// finish();
			//
			// Intent intent = new Intent(RoverSyncActivity.this,
			// RoverLiteClientActivity.class);
			// startActivity(intent);
		} catch (Exception e) {
			logger.logException("doHandleSuccess Exception", e);
		}

	}

	private void showErroDialog(final int titleId, final String titleMsg) {
		AlertDialog.Builder errorMsg = new AlertDialog.Builder(this);
		errorMsg.setTitle("Alert");
		errorMsg.setMessage(titleMsg);
		errorMsg.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
			}
		});
		errorMsg.show();
	}

	private void getlogOut() {
		try {
			
			roverApp.deleteFile(roverApp.getUserName()
					+ ApplicationContext.CUR_USER_EXT);
			roverApp.setUserName(null);
			roverApp.loggedUser = null;
			roverApp.getViewContext().clear();
			Intent myIntent = new Intent(this, RoverLiteClientActivity.class);
			myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(myIntent);
			finish();
		} catch (Exception e) {
			logger.logException("get LogOut", e);
		}
	}



}
